package top.someapp.dxf2dsvg.dxf;

import top.someapp.dxf2dsvg.base.Point;
import top.someapp.dxf2dsvg.entity.Entities;
import top.someapp.dxf2dsvg.entity.Entity;
import top.someapp.dxf2dsvg.kits.Numbers;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;

/**
 * autocad 中的块
 *
 * @author zwz
 * Created on 2020-04-18
 */
public class Block {
    final String name;
    String layerName;
    Point basePoint;
    List<Entity> entityList = new ArrayList<>(); // 块中的图元
    Entity entity;

    Block(@Nonnull String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public String getLayerName() {
        return layerName;
    }

    public Block setLayerName(@Nonnull String layerName) {
        this.layerName = layerName;
        return this;
    }

    public Block setup(@Nonnull Item item) {
        if (entityList.isEmpty()) {
            if (basePoint == null) {
                basePoint = new Point();
            }
            if (item.code == 10 || item.code == 20 || item.code == 30) {
                if (item.code == 10) {
                    basePoint.setX(Numbers.floatValue(item.value));
                } else if (item.code == 20) {
                    basePoint.setY(Numbers.floatValue(item.value));
                } else {
                    basePoint.setZ(Numbers.floatValue(item.value));
                }
                return this;
            }
        }
        if (item.code == 0) { // a new entity start
            String type = item.value;
            entity = Entities.make(type);
            entity.setBasePoint(basePoint);
            entityList.add(entity);
        } else if (item.code == 8) { // layer name
            setLayerName(item.value);
        } else { // previous entity continues
            if (entity != null) {
//                System.out.println("entity " + entity.type() + " setup with: " + item);
                entity.setup(item);
            }
        }
        return this;
    }

    @Override
    public String toString() {
        return "Block{" +
                "name='" + name + '\'' +
                ", layerName='" + layerName + '\'' +
                ", entityList=" + entityList +
                '}';
    }
}
